#include "CircularQueue.h"

CircularQueue* init_queue() {
    CircularQueue* queue = (CircularQueue*)malloc(sizeof(CircularQueue));
    queue->front = queue->rear = 0;
    return queue;
}

int is_empty(CircularQueue* queue) { return queue->front == queue->rear; }

int is_full(CircularQueue* queue) {
    return (queue->rear + 1) % MAX_SIZE == queue->front;
}

int size(CircularQueue* queue) {
    return (queue->rear - queue->front + MAX_SIZE) % MAX_SIZE;
}

int enqueue(CircularQueue* queue, ElemType data) {
    if (is_full(queue)) {
        printf("enqueue: Queue is full\n");
        return 0;
    }
    queue->data[queue->rear] = data;
    queue->rear = (queue->rear + 1) % MAX_SIZE;
    return 1;
}

ElemType dequeue(CircularQueue* queue) {
    if (is_empty(queue)) {
        printf("dequeue: Queue is empty\n");
        return -1;
    }
    ElemType ret = queue->data[queue->front];
    queue->front = (queue->front + 1) % MAX_SIZE;
    return ret;
}

ElemType front(CircularQueue* queue) {
    if (is_empty(queue)) {
        printf("front: Queue is empty\n");
        return -1;
    }
    return queue->data[queue->front];
}

ElemType rear(CircularQueue* queue) {
    if (is_empty(queue)) {
        printf("rear: Queue is empty\n");
        return -1;
    }
    return queue->data[(queue->rear - 1 + MAX_SIZE) % MAX_SIZE];
}

void dequeue_all(CircularQueue* queue) {
    printf("[FRONT << ");
    while (!is_empty(queue)) {
        printf("%d << ", dequeue(queue));
    }
    printf("REAR]\n");
}

void clear_queue(CircularQueue* queue) {
    queue->front = queue->rear = 0;
    free(queue);
    // 在调用clear_queue函数后，需要将队列的指针设置为NULL，以避免出现野指针。
}
